<template>
  <div class="rectification-manager" ref="rectification">
    <div class="rectification-container">
      <div class="filter-container">
        <el-form :model="tableParams" label-width="80">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="判责单号">
                <el-input placeholder="请输入" v-model="tableParams.assignBlameNo" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="责任人">
                <el-input placeholder="请输入" v-model="tableParams.assignBlameUserName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发起时间">
                <el-date-picker
                  v-model="dateRange"
                  :clearable="false"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  @change="e => changeTime(e, 1)"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联客户">
                <el-input placeholder="请输入" v-model="tableParams.customerName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="售后类型">
                <el-select placeholder="请选择" v-model="tableParams.afterSalesType">
                  <el-option label="整改" :value="1" />
                  <el-option label="增减项" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="判责状态">
                <el-select multiple placeholder="选选择" v-model="tableParams.assignBlameStateList">
                  <el-option v-for="item in judgmentStatus" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="售后状态">
                <el-select multiple placeholder="请选择" v-model="tableParams.reformStateList">
                  <el-option :label="item.text" :value="item.value" v-for="item in statusMap" :key="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核实时间">
                <el-date-picker
                  v-model="timeData"
                  :clearable="false"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  @change="e => changeTime(e, 2)"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="filter-container-buttons">
                <el-button type="primary" :icon="Search" @click="handelSearch">查询</el-button>
                <el-button type="primary" plain :icon="RefreshRight" @click="handelResetFilter">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="tabs-sticky">
        <div class="tabs-content">
          <el-tabs class="demo-tabs" v-model="tableParams.pageType" @tab-change="handleTabsChange">
            <el-tab-pane :name="0" label="全部"></el-tab-pane>
            <el-tab-pane :name="1">
              <template #label>
                <span class="custom-tabs-label">
                  <span>需判责</span> <span v-if="stateCounts?.assignBlameNum">({{ stateCounts?.assignBlameNum }})</span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane :name="2">
              <template #label>
                <span class="custom-tabs-label">
                  <span>需核实</span> <span v-if="stateCounts?.verifyNum">({{ stateCounts?.verifyNum }})</span>
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="table-container-filter">
          <el-button style="width: 140px" type="primary" plain @click="handelExport" :loading="isLoadingExport"
            >按查询条件导出
          </el-button>
        </div>
      </div>
      <div class="table-container" element-loading-text="数据加载中..." v-loading="isLoadingTable">
        <el-table
          ref="reformTableRef"
          :data="tableData"
          stripe
          style="width: 100%"
          border
          :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
          reserve-selection
          row-key="reformId"
          :height="tableHeight"
          @selection-change="selectionChange"
        >
          <el-table-column type="selection" reserve-selection width="55" fixed="left" />
          <el-table-column prop="" label="售后类型" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.afterSalesType === 1 ? "整改" : "增减项" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="售后分类" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ reformTypeLabel(row).value }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="customerName" label="关联客户" show-overflow-tooltip />
          <el-table-column label="问题描述" show-overflow-tooltip prop="reformDesc" />
          <el-table-column label="预计判责金额" show-overflow-tooltip prop="assignBlameAmount" width="120"/>
          <el-table-column label="公司承担金额" show-overflow-tooltip prop="companyBorneAmount" width="120"/>
          <el-table-column label="已核销金额" show-overflow-tooltip prop="clearedAmount" />
          <el-table-column label="责任人" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.assignBlameUserNames">{{ row.assignBlameUserNames }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="判责状态" width="100" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="judgment-status" :class="`judgment-status-${judgmentLabel(row).value[0]}`">
                {{ judgmentLabel(row).value[1] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="售后状态" width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="reform-state" :class="`reform-state-${reformMapLabel(row).value[0]}`">
                {{ reformMapLabel(row).value[1] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="售后单号" show-overflow-tooltip prop="reformNo" />
          <el-table-column prop="submitTime" label="发起时间" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="assignBlameNo" label="判责单号" show-overflow-tooltip />
          <el-table-column prop="verifiedTime" label="核实时间" show-overflow-tooltip />
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row }">
              <div class="table-operate" v-if="row.assignBlameState !== 11 && row.reformState !== 6">
                <el-button v-for="button in getVisibleButtons(row)" :key="button.text" type="primary" link @click="button.action">
                  {{ button.text }}
                </el-button>
                <div v-if="showDropdownitem(row)">
                  <el-dropdown>
                    <span class="el-dropdown-link" style="font-size: 14px"
                      >展开
                      <el-icon class="el-icon--left">
                        <arrow-down />
                      </el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="item in filteredDropdownItems(row)"
                          :key="item.command"
                          :command="item.command"
                          @click="item.action"
                        >
                          <el-button type="text" style="height: 22px">{{ item.text }}</el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <custom-pagination
      :total="listTotal"
      v-model:limit="tableParams.size"
      v-model:page="tableParams.current"
      layout="total, slot, prev, pager, next, jumper"
      @pagination="handelPage"
    >
    </custom-pagination>
    <!-- 核实弹窗   -->
    <div class="verify-dialog">
      <el-drawer v-model="centerDialogVisible" :show-close="false">
        <template #header>
          <div class="drawer-header">
            <div class="drawer-header-icon"></div>
            <div>核实<span>（仅停用状态的员工和供应商可操作核实）</span></div>
          </div>
        </template>
        <template #default>
          <div>
            <div>请选择需要核实的责任人</div>
            <div
              class="drawer-body"
              v-for="item in dataList"
              :key="item"
              :class="{ 'drawer-body-active': checkList.includes(item) }"
            >
              <div class="drawer-body-header">
                <div style="display: flex; align-items: center">
                  <div class="line"></div>
                  责任人：{{ item.userName }}
                </div>
                <div @click="handleActive(item)">
                  <img
                    style="width: 24px; height: 24px"
                    v-if="checkList.includes(item)"
                    src="@/assets/images/active.png"
                    alt=""
                  />
                  <img style="width: 24px; height: 24px" v-else src="@/assets/images/cancel.png" alt="" />
                </div>
              </div>
              <div class="drawer-body-card" v-if="item.roleName">
                <div style="color: #86909c">责任角色</div>
                <div style="color: #3d3d3d">{{ item.roleName }}</div>
              </div>
              <div class="drawer-body-card" v-if="item.type">
                <div style="color: #86909c">合作方类型</div>
                <div style="color: #3d3d3d">{{ typeList[item.type - 1] }}</div>
              </div>
              <div class="drawer-body-card">
                <div style="color: #86909c">判责金额</div>
                <div style="color: #3d3d3d">¥{{ item.amount }}</div>
              </div>
            </div>
          </div>
        </template>
        <template #footer>
          <div style="text-align: center" class="verify-dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleVerifyOk">确定核实</el-button>
          </div>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<script setup>
import { nextTick, onActivated, ref } from "vue";
import { ArrowDown, RefreshRight, Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { documentFlow } from "@/utils/downFile";
import useComputedParams from "@/hooks/useComputedParams";
import { judgmentStatus, statusMap } from "./config";
import useTagsViewStore from "@/store/modules/tagsView";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import { judgePage, stateCount, rectificationExport, verified, sendStaffConfirm, revokeStaffMsg, verify } from "@/apis/judgment";

const router = useRouter();
const tagsViewStore = useTagsViewStore();
const stateCounts = ref(null);
const centerDialogVisible = ref(false);
const isLoadingTable = ref(false);
const dataList = ref([]);
const checkList = ref([]);
const typeList = ref(["客户", "供应商 ", "其他", "项目经理 ", "物流运输 ", "工人", "员工"]);
const tableHeight = ref(0);
const rectification = ref();
const initTableParams = {
  current: 1,
  size: 10,
  assignBlameNo: "",
  assignBlameUserName: "",
  beginAssignBlameTime: "",
  endAssignBlameTime: "",
  customerName: "",
  afterSalesType: "",
  assignBlameStateList: [],
  reformStateList: [],
  pageType: 0
};
const dateRange = ref([]);
const timeData = ref([]);
const tableParams = ref({ ...initTableParams });
const tableData = ref([]);
const listTotal = ref(0);
const disabledDate = time => {
  const now = dayjs().startOf("date");
  return time.valueOf() > now.valueOf();
};
const changeTime = (time, type) => {
  if (time) {
    const startDate = new Date(time[0]);
    const endDate = new Date(time[1]);
    const diff = endDate.getTime() - startDate.getTime();
    const diffInDays = diff / (1000 * 60 * 60 * 24);
    const diffInYears = diffInDays / 365;
    if (diffInYears > 2) {
      if (type === 1) {
        dateRange.value = [];
      } else {
        timeData.value = [];
      }
      ElMessage({ message: "最大时间跨度为2年,请重新选择！", type: "error" });
    }
  }
};
const setDate = () => {
  // 默认选中六个时间
  const recentSixMonths = getRecentSixMonthsRange();
  dateRange.value = [recentSixMonths.start, recentSixMonths.end];
};

setDate();
const getStateCount = async () => {
  const { data } = await stateCount(handelConditions());
  stateCounts.value = data || null;
};
// 选择售后状态
const handleTabsChange = e => {
  tableParams.value.pageType = e;
  handelSearch();
};
const buttons = row => {
  return [
    {
      command: 0,
      condition: () => row.assignBlameState !== 11,
      text: "详情",
      action: () => handelGoDetail(row)
    },
    {
      command: 1,
      condition: () => ![10, 11].includes(row.assignBlameState),
      text: "判责",
      action: () => handelJudgment(row)
    },

    {
      command: 2,
      condition: () => row.verify,
      text: "核实",
      action: () => handleVerify(row)
    },
    {
      command: 3,
      condition: () => row.confirm,
      text: "发起确认",
      action: () => handleRevocation(row, 0)
    },
    {
      command: 4,
      condition: () => row.withdrawl,
      text: "撤回确认",
      action: () => handleRevocation(row, 1)
    }
  ];
};
//定义按钮
const getVisibleButtons = row => {
  // 过滤可见按钮
  const filteredButtons = buttons(row).filter(btn => btn.condition());
  return filteredButtons.length <= 2 ? filteredButtons : [filteredButtons[0]];
};
//判断按钮显示个数是否大于2 大于2返回true
const showDropdownitem = row => {
  const arryButtonCount = buttons(row).reduce((count, item) => count + item.condition(), 0);
  return arryButtonCount > 2;
};
// 过滤掉第一个满足条件的下拉项
const filteredDropdownItems = row => {
  const visibleItems = buttons(row).filter(item => item.condition());
  visibleItems.shift();
  return visibleItems;
};

// 工具函数，用于计算最近六个月的日期范围
function getRecentSixMonthsRange() {
  const now = dayjs();
  const start = now.subtract(6, "month").format("YYYY-MM-DD");
  const end = now.format("YYYY-MM-DD");
  return {
    start,
    end
  };
}

// 撤销审批
const handleRevocation = (row, i) => {
  const nameList = ["发起确认", "撤回确认通知"];
  const textList = ["确定发起确认通知？", "本次会撤销判责单中所有未确认的消息通知，确定撤回？"];
  ElMessageBox.confirm(textList[i], nameList[i], {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    center: true,
    customClass: "message-box",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        switch (i) {
          case 0:
            const { data } = await sendStaffConfirm(row.reformId);
            ElMessage({
              type: data ? "success" : "error",
              message: data ? "发起确认成功" : "发起确认失败"
            });
            initData();
            done();
            break;
          case 1:
            await revokeStaffMsg(row.reformId);
            ElMessage({
              type: "success",
              message: "撤回确认成功"
            });
            initData();
            done();
            break;
        }
      } else {
        done();
      }
    }
  });
};
// 查询参数
const handelConditions = () => {
  const postData = tableParams.value;
  if (dateRange.value?.length >= 2) {
    postData.beginAssignBlameTime = dateRange.value[0];
    postData.endAssignBlameTime = dateRange.value[1];
  }
  if (timeData.value?.length >= 2) {
    postData.beginVerifiedTime = timeData.value[0];
    postData.endVerifiedTime = timeData.value[1];
  }
  return postData;
};
// 获取列表数据
const getRectificationManagerList = async () => {
  try {
    isLoadingTable.value = true;
    const { data } = await judgePage(handelConditions());
    tableData.value = data?.list ?? [];
    listTotal.value = data?.total ?? 0;
    isLoadingTable.value = false;
  } catch (err) {
    isLoadingTable.value = false;
  }
};
const setHeight = () => {
  nextTick(() => {
    tableHeight.value = rectification.value?.getBoundingClientRect().height - 219;
  });
};
// 分页查询
const handelPage = () => {
  tableData.value = [];
  getRectificationManagerList();
  getStateCount();
};
// 详情
const handelGoDetail = data => {
  router.push({
    path: "/judgment-details",
    query: {
      reformId: data.reformId
    }
  });
};

/**
 * 过滤
 */
const handelSearch = () => {
  tableParams.value.current = 1;
  tableData.value = [];
  getRectificationManagerList();
  getStateCount();
};
const handelResetFilter = () => {
  tableParams.value = {
    ...initTableParams
  };
  timeData.value = [];
  setDate();
  getRectificationManagerList();
  getStateCount();
};

/**
 * 批量核实
 */

const selectedReformIds = ref([]);
// 只能选择已判责、已核实任务进行核实
const selectionChange = val => {
  selectedReformIds.value = val.map(item => item.reformId);
};
/**
 * 根据条件导出
 */
const isLoadingExport = ref(false);
const handelExport = async () => {
  try {
    isLoadingExport.value = true;
    const res = await rectificationExport(handelConditions());
    isLoadingExport.value = false;
    documentFlow(res, "判责管理", "xlsx");
  } catch (err) {
    isLoadingExport.value = false;
  }
};

/**
 * 判责
 */
const reformId = ref("");
// TODO:判责责任人回显，没有部门
const handelJudgment = row => {
  reformId.value = row.reformId;
  router.push({ path: "/judgment-add", query: { reformId: row.reformId } });
};
/**
 * 状态
 */
const judgmenMap = new Map([
  [1, ["warning", "未判责"]],
  [3, ["success", "已核实"]],
  [4, ["danger", "审批未通过"]],
  [5, ["warning", "待发起确认"]],
  [6, ["primary", "确认中"]],
  [7, ["success", "已确认"]],
  [8, ["danger", "责任人拒绝"]],
  [9, ["primary", "核实中"]],
  [10, ["primary", "审批中"]],
  [11, ["info", "已作废"]]
]);
const judgmentLabel = useComputedParams(data => {
  return judgmenMap.has(data.assignBlameState) ? judgmenMap.get(data.assignBlameState) : ["danger", "未知"];
});
const reformMap = new Map([
  [1, ["warning", "待审核"]],
  [2, ["warning", "待开始"]],
  [3, ["primary", "进行中"]],
  [4, ["success", "已完成"]],
  [5, ["danger", "未通过"]],
  [6, ["info", "已作废"]],
  [7, ["primary", "审批中"]],
  [8, ["warning", "待发起客户确认"]],
  [9, ["primary", "客户确认中"]],
  [10, ["danger", "客户拒绝"]],
  [11, ["warning", "待收款"]]
]);
const reformMapLabel = useComputedParams(data => {
  return reformMap.has(data.reformState) ? reformMap.get(data.reformState) : ["danger", "未知"];
});
/**
 * 分类
 */
const reformTypeLabel = useComputedParams(data => {
  let html = "";
  if (data.firstReformTypeName) {
    html += data.firstReformTypeName + "-";
  }
  if (data.secondReformTypeName) {
    html += data.secondReformTypeName + "-";
  }
  if (data.reformTypeName) {
    html += data.reformTypeName;
  }
  return html;
});

const initData = () => {
  tagsViewStore.isRefresh = false;
  getStateCount();
  getRectificationManagerList();
};

onActivated(() => {
  tagsViewStore.isRefresh && handelResetFilter();
});

const handleVerify = async row => {
  checkList.value = [];
  reformId.value = row.reformId;
  centerDialogVisible.value = true;
  const { data } = await verified(row.reformId);
  dataList.value = data;
};
// 核实
const handleVerifyOk = async () => {
  console.log(checkList.value);
  if (checkList.value.length > 0) {
    await verify(checkList.value);
    ElMessage.success("核实成功");
    centerDialogVisible.value = false;
    initData();
  } else {
    ElMessage.error("请选择核实的责任人");
  }
};
// 选择责任人
const handleActive = item => {
  if (checkList.value.indexOf(item) === -1) {
    checkList.value.push(item);
  } else {
    checkList.value.splice(checkList.value.indexOf(item), 1);
  }
};
initData();
setHeight();
</script>

<style scoped lang="scss">
@use "index";
</style>
<style lang="scss" scoped>
@use "@/assets/styles/mixin";

.rectification-manager {
  height: calc(100% - 20px);
  padding: 0 20px 20px;
  background-color: #fff;
  overflow-y: scroll;
  box-shadow: 4px 5px 16px 0 rgba(0, 0, 0, 0.04);
  border-radius: 8px;

  &__header {
    position: relative;
  }

  &__buts {
    position: absolute;
    right: 0;
    top: 0;
  }
}

.select-user-popper {
  border: 1px solid #0052d9 !important;
  box-shadow: 0 0 0 2px #d9e1ff !important;
  border-radius: 3px;

  .el-select-dropdown__header {
    padding: 10px 5px 4px 5px !important;
  }

  .el-scrollbar__view > .el-select-dropdown__item {
    @include mixin.flex-align;
    padding-left: 10px;
    padding-right: 10px;
    //font-size: 12px;
    color: #3d3d3d;
    line-height: 22px;
  }

  .el-popper__arrow::before {
    display: none;
  }
}

.tabs-sticky {
  position: sticky;
  top: 0px;
  background: #ffffff;
  z-index: 99;
}
</style>
